package com.ericsson.enap.modules.cdr.thread;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.*;
import org.slf4j.Logger;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 下载SFTP VGCCDR线程（根据VGCCG下载目录划分）
 */
public class VGCCGCDRDownLoadSftpThread implements Runnable{

    private static Logger log = LoggerUtils.Logger(LogFileName.VgcCdrDownLoadJob);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    private FTPInfoVO ftpInfo;
    private String imsDownloadDir;
    private String vgcCdrDownloadInterval;
    private String fileNameType;
    private RedisCache redisCache;
    private String redisKey="vgc:cdr:download:";


    public VGCCGCDRDownLoadSftpThread(String fileNameType, FTPInfoVO ftpInfo, String imsDownloadDir, String vgcCdrDownloadInterval, RedisCache redisCache) throws ParseException {
        this.fileNameType=fileNameType;
        this.ftpInfo = ftpInfo;
        this.imsDownloadDir=imsDownloadDir;
        this.redisCache=redisCache;
        this.vgcCdrDownloadInterval=vgcCdrDownloadInterval;
    }
    @Override
    public void run() {
        String dirpath = ftpInfo.getPath();
        log.info("begin start-----------------------" + " dirpath :" + dirpath + "---------------------");

        SFtpCarrierUtilNew ftpCarrier = new SFtpCarrierUtilNew(ftpInfo,log);
        long nowTime = System.currentTimeMillis();
        Date nowDate = new Date(nowTime);
        //当天“已下载文件集合”
        Set<String> nowFileDone=redisCache.getCacheSet(redisKey+formatter.format(nowDate)+":"+ftpInfo.getCdrPathId());
        //前一天“已下载文件集合”
        Set<String> lastFileDone=redisCache.getCacheSet(redisKey+DateUtils.beforNumDay(nowDate,-1)+":"+ftpInfo.getCdrPathId());
        TreeSet<String> sortSet=new TreeSet<>(new Comparator<String>() {
            public int compare(String s1, String s2) {
                //以下电信话单格式
                String [] temp1=s1.split(":");
                String [] temp2=s2.split(":");
                return (temp1[2]+temp1[3]+temp1[4]).compareTo((temp2[2]+temp2[3]+temp2[4]));
                //以下移动话单格式
//                String [] temp1=s1.split(":")[1].split("_");
//                String [] temp2=s2.split(":")[1].split("_");
//                if(temp1.length==5) {
//                    //其它
//                    //OFFLINE:CHF001001_E_160100_20211020100931_00335794.dat:20211020:NO-LABEL.gz
//                    //ZERO:CHF001001_E_160100_20211020100931_00055003.dat:20211020:NO-LABEL.gz
//                    //ONLINE:CHF001001_E_160100_20211020100931_00379674.dat:20211020:NO-LABEL.gz
//                    return (temp1[3] + temp1[4]).compareTo((temp2[3] + temp2[4]));
//                }else{
//                    //CDF:CDF3:CDF3_20211020100847_27989.ber:20211020:NO-LABEL.gz
//                    return (temp1[1] + temp1[2]).compareTo((temp2[1] + temp2[2]));
//                }
            }
        });
        if(nowFileDone!=null&&nowFileDone.size()>0) {
            Iterator it = nowFileDone.iterator();
            while(it.hasNext()) {
                TreeSet<String> strSet = (TreeSet) it.next();
                for (String str : strSet) {
                    sortSet.add(str);
                }
            }
        }
        if(lastFileDone!=null&&lastFileDone.size()>0) {
            Iterator it = lastFileDone.iterator();
            while(it.hasNext()) {
                TreeSet<String> strSet = (TreeSet) it.next();
                for (String str : strSet) {
                    sortSet.add(str);
                }
            }
        }
        boolean down=true;
        long loadFileModifyTime=0;
        if(sortSet.size()>0) {
            //以下电线话单文件格式
            String[] subStr = sortSet.last().split(":");
            try {
                loadFileModifyTime= (new SimpleDateFormat("yyyyMMddHHmmSS").parse(subStr[2]+subStr[3])).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //以下移动话单文件格式
//            String[] subStr = sortSet.last().split(":")[1].split("_");
//            try {
//                if(subStr.length==5) {
//                    //其它
//                    //OFFLINE:CHF001001_E_160100_20211020100931_00335794.dat:20211020:NO-LABEL.gz
//                    //ZERO:CHF001001_E_160100_20211020100931_00055003.dat:20211020:NO-LABEL.gz
//                    //ONLINE:CHF001001_E_160100_20211020100931_00379674.dat:20211020:NO-LABEL.gz
//                    loadFileModifyTime = (new SimpleDateFormat("yyyyMMddHHmmSS").parse(subStr[3])).getTime();
//                }else{
//                    //CDF:CDF3:CDF3_20211020100847_27989.ber:20211020:NO-LABEL.gz
//                    loadFileModifyTime = (new SimpleDateFormat("yyyyMMddHHmmSS").parse(subStr[1])).getTime();
//                }
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
        }else{
            down=false;
        }
        long beforeTime;
        if ((nowTime - loadFileModifyTime) > 2*60*60*1000) { // 当数据库中最后时间为空或与当前时间相差两小时以上时，说明系统中断，按第一次下载
            int timeIn = 0;
            try {
                // 获取系统设定的初始下载时间差
                timeIn = Integer.parseInt(vgcCdrDownloadInterval);
            } catch (Exception e) {
                log.info("CDRDownLoadTask类>>系统设置的初始化下载时间差不正确,properties文件中的cdrJobInterval参数");
            }
            beforeTime = nowTime - timeIn * 60000L;
            down=false;
        } else {
            beforeTime = loadFileModifyTime;
        }
        Date beforeDate = new Date(beforeTime);
        log.info("formatter.format(nowDate) :" +formatter.format(nowDate) + " formatter.format(beforeDate)) :" +formatter.format(beforeDate) + " dirpath :" + dirpath);

        // 判断是否是同一天
        if (formatter.format(nowDate).equals(formatter.format(beforeDate))) {
            // 是同一天
            log.info("sameday " + " dirpath :" + dirpath);
            Set<String> fileDownSet = ftpCarrier.download_VGCCDR(this.fileNameType,imsDownloadDir+ File.separator, formatter.format(nowDate),sortSet,down);
            this.setRedisCache(redisKey+formatter.format(nowDate)+":",String.valueOf(ftpInfo.getCdrPathId()),fileDownSet);
        } else {
            log.info("===== different day =====" + " dirpath :" + dirpath);
            // 不是同一天
            Set<String> fileDownSetBefore  = ftpCarrier.download_VGCCDR(this.fileNameType,imsDownloadDir+File.separator, formatter.format(beforeDate),sortSet,down);
            this.setRedisCache(redisKey+formatter.format(beforeDate)+":",String.valueOf(ftpInfo.getCdrPathId()),fileDownSetBefore);
            ftpCarrier.disconnect();
            Set<String> fileDownSetNow  = ftpCarrier.download_VGCCDR(this.fileNameType,imsDownloadDir+ File.separator,formatter.format(nowDate),sortSet,down);
            this.setRedisCache(redisKey+formatter.format(nowDate)+":",String.valueOf(ftpInfo.getCdrPathId()),fileDownSetNow);
        }

        ftpCarrier.disconnect();
        log.info(" ===== CDRDownLoadTask execute  end============="  +" dirpath :" + dirpath);
    }

    public void setRedisCache(String prefix,String key, Set result) {
        if(null!=result&&result.size()>0) {
            redisCache.setCacheSet(prefix + key, result);
            redisCache.expire(prefix + key, 2, TimeUnit.DAYS);
        }
    }
}
